<!-- ERP 产品列表 -->
<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="150px"
    >
      <el-form-item label="客户名称/编号" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="所属行业" prop="industry">
        <el-select v-model="queryParams.industry" clearable placeholder="请选择" class="!w-240px">
          <el-option
            v-for="item in industryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户来源" prop="customerSource">
        <el-select
          v-model="queryParams.customerSource"
          clearable
          placeholder="请选择"
          class="!w-240px"
        >
          <el-option
            v-for="item in customerSourceOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户标签" prop="customerTags">
        <el-select
          v-model="queryParams.customerTags"
          clearable
          placeholder="请选择"
          class="!w-240px"
        >
          <el-option
            v-for="item in customerTagsOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="跟进进度" prop="followProgress">
        <el-select
          v-model="queryParams.followProgress"
          clearable
          placeholder="请选择"
          class="!w-240px"
        >
          <el-option
            v-for="item in followProgressOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客户分类" prop="customerCategory">
        <el-select
          v-model="queryParams.customerCategory"
          clearable
          placeholder="请选择"
          class="!w-240px"
        >
          <el-option
            v-for="item in customerCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人姓名" prop="contractName">
        <el-input
          v-model="queryParams.contractName"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="联系人手机号码" prop="contractNumber">
        <el-input
          v-model="queryParams.contractNumber"
          placeholder="请输入"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="线索类别" prop="clueCategory">
        <el-select
          v-model="queryParams.clueCategory"
          clearable
          placeholder="请选择"
          class="!w-240px"
        >
          <el-option
            v-for="item in customerCategoryOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="领用时间" prop="acceptanceTime">
        <el-date-picker
          v-model="queryParams.acceptanceTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['erp:product:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['erp:product:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-row :gutter="10" class="w-full" style="margin-bottom: 16px; justify-content: flex-end">
      <div class="flex items-center">
        <el-col :span="10.1">
          <div>
            <el-button type="default" plain @click="btnLie">
              <img key="1" alt="" width="25px" height="20px" src="@/assets/svgs/column.svg" />
              列表字段
            </el-button>
          </div>
        </el-col>
      </div>
    </el-row>
    <el-table v-loading="loading" :data="list" :show-overflow-tooltip="true">
      <el-table-column
        label="客户名称"
        align="center"
        prop="customerName"
        v-if="visibleColumns.customerName"
        min-width="150"
      />
      <el-table-column
        label="线索标签"
        align="center"
        prop="tag"
        v-if="visibleColumns.tag"
        min-width="150"
      >
        <template #default="scope">
          <div class="tag-display" @click="openTagDialog(scope.row)">
            <el-icon :size="size" :color="color">
              <Edit />
            </el-icon>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="客户编码"
        align="center"
        prop="customerCode"
        v-if="visibleColumns.customerCode"
        width="120"
      />
      <el-table-column
        label="联系人"
        align="center"
        prop="contactName"
        v-if="visibleColumns.contactName"
        width="100"
      />
      <el-table-column
        label="企业电话"
        align="center"
        prop="companyPhone"
        v-if="visibleColumns.companyPhone"
        width="120"
      />
      <el-table-column
        label="网站电话"
        align="center"
        prop="websitePhone"
        v-if="visibleColumns.websitePhone"
        width="120"
      />
      <el-table-column
        label="所属行业"
        align="center"
        prop="industry"
        v-if="visibleColumns.industry"
        width="120"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_CUSTOMER_INDUSTRY" :value="scope.row.industry" />
        </template>
      </el-table-column>
      <el-table-column
        label="省份"
        align="center"
        prop="province"
        v-if="visibleColumns.province"
        width="80"
      />
      <el-table-column
        label="城市"
        align="center"
        prop="city"
        v-if="visibleColumns.city"
        width="80"
      />
      <el-table-column
        label="销售人员"
        align="center"
        prop="salespersonName"
        v-if="visibleColumns.salespersonName"
        width="100"
      />
      <el-table-column
        label="日期"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180"
      />
      <el-table-column
        label="客户分类"
        align="center"
        prop="categoryName"
        v-if="visibleColumns.categoryName"
        width="100"
      />
      <el-table-column
        label="客户来源"
        align="center"
        prop="source"
        v-if="visibleColumns.source"
        width="120"
      >
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.CRM_CUSTOMER_SOURCE" :value="scope.row.source" />
        </template>
      </el-table-column>
      <el-table-column
        label="跟进进度"
        align="center"
        prop="followProgress"
        v-if="visibleColumns.followProgress"
        width="100"
      />
      <el-table-column
        label="洽谈进度"
        align="center"
        prop="negotiationProgress"
        v-if="visibleColumns.negotiationProgress"
        width="100"
      />
      <el-table-column
        label="被共享人"
        align="center"
        prop="sharedPersonNames"
        v-if="visibleColumns.sharedPersonNames"
        min-width="120"
      />
      <el-table-column label="操作" align="center" fixed="right" width="250">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('detail', scope.row.id)"
            v-hasPermi="['erp:product:update']"
          >
            客户详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openReturnForm('', scope.row.customerName)"
            v-hasPermi="['erp:product:update']"
          >
            回访提醒
          </el-button>
          <el-button
            link
            type="primary"
            @click="openQTJDnForm('create', scope.row)"
            v-hasPermi="['erp:product:delete']"
          >
            添加进度
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>
  <!-- 添加标签编辑弹窗 -->
  <el-dialog v-model="tagDialogVisible" title="选择客户标签" width="500px">
    <el-form :model="tagForm" label-width="60px">
      <el-input v-model="currentRow.mes" placeholder="请输入" />
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleTagCancel">取消</el-button>
        <el-button type="primary" @click="handleTagConfirm"> 保存 </el-button>
      </span>
    </template>
  </el-dialog>

  <!-- 自定义字段 -->
  <el-dialog v-model="dialogVisible" title="自定义字段" width="50%" :before-close="handleClose">
    <div class="content">
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.customerName" label="客户名称" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.tag" label="线索标签" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.customerCode" label="客户编码" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.contactName" label="联系人" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.companyPhone" label="企业电话" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.websitePhone" label="网站电话" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.industry" label="所属行业" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.province" label="省份" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.city" label="城市" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.salespersonName" label="销售人员" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.categoryName" label="客户分类-" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.source" label="客户来源" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.followProgress" label="跟进进度" size="large"
      /></div>
       <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.remark" label="备注" size="large"
      /></div>
       <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.contractNumber" label="联系电话" size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox
          v-model="tempVisibleColumns.negotiationProgress"
          label="洽谈进度"
          size="large"
      /></div>
      <div class="content-list"
        ><el-checkbox v-model="tempVisibleColumns.sharedPersonNames" label="被共享人" size="large"
      /></div>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm"> 确定 </el-button>
      </span>
    </template>
  </el-dialog>

  <CustomerForm ref="formRef" @success="getList" />
  <ReturnReminderForm ref="reminderFormRef" @success="getList" />
  <NegotiationProgress ref="nProgressFormRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { ProductApi, ProductVO } from '@/api/erp/product/product'
import { ProductCategoryApi, ProductCategoryVO } from '@/api/erp/product/category'
import { DICT_TYPE } from '@/utils/dict'
import { defaultProps, handleTree } from '@/utils/tree'
import { erpPriceTableColumnFormatter } from '@/utils'
import CustomerForm from '../customer/CustomerForm.vue'
import ReturnReminderForm from './components/returnreminderForm.vue'
import NegotiationProgress from './components/negotiationProgress.vue'
import { fa } from 'element-plus/es/locale'
/** ERP 产品列表 */
defineOptions({ name: 'ErpProduct' })
const dialogVisible = ref(false)
const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const loading = ref(true) // 列表的加载中
const list = ref<ProductVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  customerName: undefined,
  industry: undefined,
  customerSource: undefined,
  customerTags: undefined,
  followProgress: undefined,
  customerCategory: undefined,
  contractName: undefined,
  contractNumber: undefined,
  clueCategory: undefined,
  acceptanceTime: undefined,
  createTime: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中
const categoryList = ref<ProductCategoryVO[]>([]) // 产品分类列表

/** 查询列表 */
// const getList = async () => {
//   loading.value = true
//   try {
//     const data = await ProductApi.getProductPage(queryParams)
//     list.value = data.list
//     total.value = data.total
//   } finally {
//     loading.value = false
//   }
// }
const getList = async () => {
  loading.value = true
  try {
    // 模拟数据开始
    const mockData = [
      {
        id: 10001,
        customerName: '星耀科技有限公司',
        tags: ['重点客户', '高潜力'],
        customerCode: 'KH-202309-001',
        contactName: '张明',
        companyPhone: '0571-87654321',
        websitePhone: '400-123-4567',
        industry: 3, // 科技行业
        province: '浙江',
        city: '杭州',
        salespersonName: '李经理',
        createTime: '2023-09-15 14:30:22',
        categoryName: '企业客户',
        source: 2, // 线上来源
        followProgress: 65,
        negotiationProgress: 40,
        sharedPersonNames: '王总监,刘助理'
      },
      {
        id: 10002,
        customerName: '华东制造集团',
        tags: ['长期合作', 'VIP'],
        customerCode: 'KH-202309-002',
        contactName: '陈思思',
        companyPhone: '021-76543210',
        websitePhone: '800-222-3333',
        industry: 5, // 制造业
        province: '上海',
        city: '浦东',
        salespersonName: '赵总监',
        createTime: '2023-09-18 10:15:37',
        categoryName: '集团客户',
        source: 1, // 线下推荐
        followProgress: 85,
        negotiationProgress: 70,
        sharedPersonNames: '孙经理,钱顾问'
      }
    ]

    list.value = mockData
    total.value = 2
    // 模拟数据结束
  } finally {
    loading.value = false
  }
}
/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}
// 添加弹窗和表单状态
const tagDialogVisible = ref(false)
const currentRow = ref({}) // 存储当前编辑行
const tagForm = reactive({
  selectedTags: [] // 存储选中的标签
})

// 定义标签选项
const customerTagsOptions = [
  { value: 1, label: '潜在客户' },
  { value: 2, label: '重要客户' },
  { value: 3, label: 'VIP客户' },
  { value: 4, label: '流失风险' }
]

// 打开标签编辑弹窗
const openTagDialog = (row) => {
  currentRow.value = row
  tagForm.selectedTags = row.tagIds || []
  tagDialogVisible.value = true
}

// 保存标签
const handleTagConfirm = () => {
  message.success(t('common.createSuccess'))
  tagDialogVisible.value = false
}

const handleTagCancel = () => {
  tagDialogVisible.value = false
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 回访提醒表单操作 */
const reminderFormRef = ref()
const openReturnForm = (type: string, name?: string) => {
  reminderFormRef.value.open(type, name)
}
/** 回访提醒表单操作 */
const nProgressFormRef = ref()
const openQTJDnForm = (type: string, name?: string) => {
  nProgressFormRef.value.open(type, name)
}
/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await ProductApi.deleteProduct(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await ProductApi.exportProduct(queryParams)
    download.excel(data, '客户跟进表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
const visibleColumns = ref({
  customerName: true,
  customerCode: true,
  industry: true,
  contactName: true,
  companyPhone: true,
  websitePhone: true,
  city: true,
  tag:true,
  salespersonName: true,
  categoryName: true,
  source: true,
  followProgress: true,
  negotiationProgress: true,
  customerSource: true,
  customerTags: true,
  sharedPersonNames: true,
  contractName: true,
  contractNumber: false,
  clueCategory: true,
  acceptanceTime: true,
  createTime: true,
  province: true
})
const tempVisibleColumns = ref({ ...visibleColumns.value })
const btnLie = () => {
  tempVisibleColumns.value = { ...visibleColumns.value }
  dialogVisible.value = true
}
const handleClose=()=>{
  dialogVisible.value = false
}
const handleCancel = () => {
  dialogVisible.value = false
}

// 列表字段确认操作
const handleConfirm = () => {
  visibleColumns.value = { ...tempVisibleColumns.value }
  dialogVisible.value = false
}
/** 初始化 **/
onMounted(async () => {
  await getList()
  // 产品分类
  const categoryData = await ProductCategoryApi.getProductCategorySimpleList()
  categoryList.value = handleTree(categoryData, 'id', 'parentId')
})
</script>
